<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, toRefs } from "vue";
// import { queryCheckAreaTree } from "@/api/erc/inspectPlan";
import { delWorkItem, page, setDone } from "@/api/erc/workItem";
import dayjs from "dayjs";
import { PxMessage, PxMessageBox } from "px-ui";
import AddWork from "./components/AddWork.vue";
import DetailWork from "./components/DetailWork.vue";
const initParams = {
  timeRange: [],
  startTime: "",
  endTime: "",
  pageNum: 1,
  pageSize: 20
};
const state = reactive<any>({
  queryParams: { ...initParams },
  total: 0,
  tableColumns: [
    { prop: "itemTypeDesc", label: "类型", minWidth: "80", showOverflowTooltip: true, fixed: "left" },
    { prop: "time", label: "时间", minWidth: "120", showOverflowTooltip: true },
    { prop: "facCodeDesc", label: "地块", minWidth: "140", showOverflowTooltip: true },
    { prop: "positionCodesDesc", label: "区域", minWidth: "120", showOverflowTooltip: true },
    { prop: "reason", label: "原因", minWidth: "140", showOverflowTooltip: true },
    { prop: "applicantName", label: "申请人员", minWidth: "100", showOverflowTooltip: true },
    { prop: "deptName", label: "申请部门", minWidth: "100", showOverflowTooltip: true },
    { prop: "ercName", label: "ERC人员", minWidth: "100", showOverflowTooltip: true },
    { prop: "finishStatus", label: "完结状态", minWidth: "80", showOverflowTooltip: true },
    { prop: "remark", label: "备注", minWidth: "120", showOverflowTooltip: true }
  ],
  tableData: [],
  currentData: null,
  calenderType: "",
  dialogVisible: false,
  detailVisible: false,
  // positionCodesList: [],
  formRef: null
});
const { queryParams, tableColumns, total, tableData, dialogVisible, detailVisible, currentData, formRef } = toRefs(state);
// 请求表格
const queryTable = async () => {
  const { endTime, startTime, time, ...others } = queryParams.value;
  const res = await page({
    ...others,
    startTime: startTime ? dayjs(startTime).format("YYYY-MM-DD 00:00:00") : startTime,
    endTime: endTime ? dayjs(endTime).format("YYYY-MM-DD 23:59:59") : endTime
  });
  tableData.value = res.data;
  total.value = res.total;
};
onMounted(() => {
  const today = dayjs().format("YYYY-MM-DD");
  queryParams.value.timeRange = [today, today];
  queryParams.value.startTime = today;
  queryParams.value.endTime = today;
  queryTable();
});
// 获取巡检区域
// const focusPositionCodes = async () => {
//   const data = await queryCheckAreaTree({});
//   positionCodesList.value = data || [];
// };
// 重置表格
const resetTable = () => {
  formRef.value.resetFields();
  queryParams.value = { ...initParams };
  const today = dayjs().format("YYYY-MM-DD");
  queryParams.value.timeRange = [today, today];
  queryParams.value.startTime = today;
  queryParams.value.endTime = today;

  queryTable();
};
// 新增工作项
const handleAdd = () => {
  currentData.value = null;
  dialogVisible.value = true;
};
const { proxy }: any = getCurrentInstance();
// 导出
const handleExport = async () => {
  const { endTime, startTime } = queryParams.value;
  await queryTable();
  await proxy.download(
    "post",
    "/erc/workItem/exportWorkItem",
    {
      startTime: startTime ? dayjs(startTime).format("YYYY-MM-DD 00:00:00") : startTime,
      endTime: endTime ? dayjs(endTime).format("YYYY-MM-DD 23:59:59") : endTime
    },
    "今日工作项.xlsx"
  );
  PxMessage.success("已导出");
};
// 获取开始日期及结束日期
const changeDate = val => {
  if (val && val.length > 0) {
    queryParams.value.startTime = val[0];
    queryParams.value.endTime = val[1];
  } else {
    queryParams.value.startTime = "";
    queryParams.value.endTime = "";
  }
};
const handleDone = row => {
  PxMessageBox.confirm(`是否已完成？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const { id } = row;
      await setDone({ id });
      PxMessage.success("已完成");
      queryTable();
    })
    .catch(() => {});
};
const handleShow = row => {
  currentData.value = { ...row };
  detailVisible.value = true;
};
const handleEdit = row => {
  currentData.value = { ...row };
  dialogVisible.value = true;
};
const handleDlete = row => {
  PxMessageBox.confirm(`确认删除改工作项吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await delWorkItem(row);
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
</script>

<template>
  <div>
    <div class="equip-wrap-common">
      <px-form ref="formRef" class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="8">
            <px-form-item prop="timeRange" label="日期">
              <px-date-picker
                v-model="queryParams.timeRange"
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="changeDate"
              />
            </px-form-item>
          </px-col>
          <px-col :span="16">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn">
        <px-button v-has="'ERC_CALENDAR_TODAY_ADD'" style="margin-right: 8px" type="primary" @click="handleAdd">新增工作项</px-button>
        <px-button v-has="'ERC_CALENDAR_TODAY_EXPORT'" style="margin-right: 8px" @click="handleExport">导出</px-button>
      </div>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 296px)" border>
        <px-table-column label="序号" min-width="50" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <template v-for="(item, index) in tableColumns" :key="index">
          <px-table-column
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <template v-if="item.prop === 'positionCodesDesc'" #default="scope">{{
              scope.row[item.prop] ? scope.row[item.prop].join() : "-"
            }}</template>
            <template v-else #default="scope">{{ scope.row[item.prop] ? scope.row[item.prop] : "-" }}</template>
          </px-table-column>
        </template>
        <px-table-column fixed="right" label="操作" min-width="200" align="center">
          <template #default="scope">
            <px-tooltip content="Done" placement="top">
              <px-button
                v-if="scope.row.finishStatus !== 'Done'"
                icon="CircleCheck"
                v-has="'ERC_CALENDAR_TODAY_DONE'"
                link
                type="primary"
                @click="handleDone(scope.row)"
              ></px-button>
            </px-tooltip>
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ERC_CALENDAR_SHOW_BTN'" icon="Tickets" link type="primary" @click="handleShow(scope.row)"></px-button
            ></px-tooltip>
            <px-tooltip content="编辑" placement="top">
              <px-button v-has="'ERC_CALENDAR_TODAY_EDITOR'" icon="EditPen" link type="primary" @click="handleEdit(scope.row)"></px-button
            ></px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button
                v-has="'ERC_CALENDAR_TODAY_DELETE'"
                icon="Delete"
                style="margin-right: 0"
                link
                type="primary"
                @click="handleDlete(scope.row)"
              ></px-button
            ></px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <AddWork v-model:dialogVisible="dialogVisible" :data="currentData" @refresh="queryTable" />
    <DetailWork v-model="detailVisible" :data="currentData" />
  </div>
</template>

<style lang="scss" scoped>
@import url("../../scss/table-list.scss");
</style>
